package auth

import (
	"net/http"
	"goweb/ext/app"
	"github.com/gin-gonic/gin"

	"goweb/service/auth"
	"goweb/ext/e"
	"goweb/utils/commons"
	"strconv"
)

/**
	添加来源
	修改来源
 */
func AddSource(c *gin.Context) {
	appG := app.Gin{C: c}

	sourceName := c.PostForm("SourceName")
	sourceSecName := c.PostForm("SourceSecName")
	flag := c.PostForm("flag")
	optype := c.Query("type")
	code := e.SUCCESS
	if !commons.IsUserLen(sourceName, 1) || !commons.IsUserLen(sourceSecName, 1) {
		code = e.INVALID_PARAMS
		appG.Response(http.StatusOK, code, "")
		return
	}
	atoi, err := strconv.Atoi(flag)
	if !commons.CheckErr(err) {
		code = e.INVALID_PARAMS
		appG.Response(http.StatusOK, code, "")
		return
	}
	/**
		-1:不共享token
		1:共享token
	 */
	source := auth.Source{}
	if -1 == atoi {
		source.SourceId = commons.MD5(sourceName)
	} else if 1 == atoi {
		source.SourceId = commons.MD5(sourceSecName)
	} else {
		code = e.INVALID_PARAMS
		appG.Response(http.StatusOK, code, "")
		return
	}
	source.SourceName = sourceName
	source.SourceSecId = commons.MD5(sourceSecName)
	source.SourceSecName = sourceSecName
	source.Flag = atoi

	if optype == "add" {
		if !source.AddSource() {
			code = e.INSTALL_ERROR
		}
	} else if optype == "update" {
		if !source.UpdateSource() {
			code = e.UPDATE_ERROR
		}
	} else {
		code = e.ERROR
	}

	appG.Response(http.StatusOK, code, "")
	return
}

/**
获取来源
*/

func GetAllSource(c *gin.Context) {
	var appG = app.Gin{C: c}
	source := auth.GetAllSource()

	appG.Response(http.StatusOK, 200, source)
	return
}

//func UpdateSource(c *gin.Context) {
//	sourceName := c.PostForm("SourceName")
//	sourceSecName := c.PostForm("SourceSecName")
//	flag := c.PostForm("flag")
//}

func DeleteSource(c *gin.Context) {
	id := c.PostForm("SourceSecId")
	var appG = app.Gin{C: c}
	code := e.SUCCESS
	if !commons.IsUserLen(id, 16) {
		appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
		return
	}

	source := auth.Source{}
	source.SourceSecId = id
	if !source.DeleteSource() {
		code = e.DELETE_ERROR
	}
	appG.Response(http.StatusOK, code, nil)
	return
}
